package com.doufeng.base.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doufeng.base.dto.RegisterDTO;
import com.doufeng.base.dto.UserParamDTO;
import com.doufeng.base.entity.User;
import com.doufeng.base.entity.UserProfile;
import com.doufeng.base.service.UserProfileService;
import com.doufeng.base.service.UserService;
import com.doufeng.common.result.Result;
import com.doufeng.common.util.BCryptUtil;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/base/register")
public class RegisterController {

    @Resource
    private UserService userService;
    @Resource
    private UserProfileService profileService;
    @PostMapping("/addUser")
    @Transactional
    public Result<String> register(@Valid @RequestBody RegisterDTO dto) {
        // 1. 主表重复校验
        if (userService.count(new LambdaQueryWrapper<User>().eq(User::getUsername, dto.getUsername())) > 0) {
            return Result.fail(400, "用户名已存在");
        }
        if (userService.count(new LambdaQueryWrapper<User>().eq(User::getPhone, dto.getPhone())) > 0) {
            return Result.fail(400, "手机号已存在");
        }

        // 2. 写主表
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setPassword(BCryptUtil.encode(dto.getPassword()));
        user.setPhone(dto.getPhone());
        user.setUserType(0);
        user.setStatus(0);
        userService.save(user);   // MP 回写 ID

        // 3. 写子表
        UserParamDTO param = new UserParamDTO();
        param.setBirthday(dto.getBirthday());
        param.setIdCard(dto.getIdCard());
        param.setCertificates(dto.getCertificates());

        UserProfile profile = new UserProfile();
        profile.setUserId(user.getId());
        profile.setParameter(JSONUtil.toJsonStr(param)); // Hutool 转 JSON
        profileService.save(profile);

        return Result.success("注册成功");
    }
}
